package com.star.robot.controller;

import com.star.robot.dto.CommonRequestDto;
import com.star.robot.dto.CompanyRequestDto;
import com.star.robot.dto.PageResultDto;
import com.star.robot.dto.ResultDto;
import com.star.robot.entity.Company;
import com.star.robot.enums.CompanyTypeEnum;
import com.star.robot.repository.CompanyRepository;
import com.star.robot.repository.UserRepositoty;
import com.star.robot.service.AdminService;
import com.star.robot.service.UserService;
import com.star.robot.util.DtAreaUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping(value = "/company")
public class CompanyController {

    @Autowired
    private CompanyRepository companyRepository;
    
    @Autowired
    private DtAreaUtil dtAreaUtil;

    @Autowired
    private AdminService adminService;

    @ApiOperation(value = "后台单位查询")
    @GetMapping(value = "/")
    public PageResultDto getAll( CompanyRequestDto requestDto , HttpServletRequest request){
        //转换成前端框架接收格式
        PageResultDto<Company> results = new PageResultDto<>();
        if(requestDto.getPage() != null && requestDto.getLimit() != null){
            //后端框架分页从0开始 前端框架从1开始
            if(requestDto.getPage() >= 1){
                requestDto.setPage(requestDto.getPage() - 1);
            }
            Pageable page =new PageRequest(requestDto.getPage() , requestDto.getLimit());
            Page<Company> companies = companyRepository.findAll(new Specification() {
                @Override
                public Predicate toPredicate(Root root, CriteriaQuery cq, CriteriaBuilder cb) {

                    //总条件
                    List<Predicate> conditions = new ArrayList<>();
//                    if(!StringUtils.isEmpty(requestDto.getProvinceId())){
//                        //所在地区
//                        Predicate provinceCondition = cb.equal(root.get("provinceId") ,requestDto.getProvinceId());
//                        conditions.add(provinceCondition);
//                    }

                    //有效状态
                    conditions.add(cb.equal(root.get("status") , true));

                    Long cityId = adminService.getCurrentAdminCityId(request);
                    if(cityId != null){
                        //所在地区
                        Predicate cityCondition = cb.equal(root.get("cityId") ,cityId);
                        conditions.add(cityCondition);
                    }



//                    if(!StringUtils.isEmpty(requestDto.getAreaId())){
//                        //所在地区
//                        Predicate areaCondition = cb.equal(root.get("areaId") ,requestDto.getAreaId());
//                        conditions.add(areaCondition);
//                    }
                    if(!StringUtils.isEmpty(requestDto.getName())){
                        //单位名称
                        Predicate nameCondition = cb.like(root.get("name") , "%"+requestDto.getName()+"%");
                        conditions.add(nameCondition);
                    }
                    if(requestDto.getCompanyType() != null){
                        //机构　还是　学校
                        Predicate typeCondition = cb.equal(root.get("companyType") , requestDto.getCompanyType());
                        conditions.add(typeCondition);
                    }

                    Predicate[] pre = new Predicate[conditions.size()];

                    cq.where(conditions.toArray(pre));
                    return cq.getRestriction();
                }
            } , page);


            for(Company company: companies.getContent()){
                //company.setTeams(null);
                company.setUser(null);
                String area = "";
                if (!StringUtils.isEmpty(company.getProvinceId())) {
                	area += dtAreaUtil.getAreaName(Long.valueOf(company.getProvinceId()));
				}              
                if (!StringUtils.isEmpty(company.getCityId())) {
                	if (area.length()>0) {
                		area += "-";
					}
                	area += dtAreaUtil.getAreaName(Long.valueOf(company.getCityId()));
				}    
                if (!StringUtils.isEmpty(company.getAreaId())) {
                	if (area.length()>0) {
                		area += "-";
					}
                	area += dtAreaUtil.getAreaName(Long.valueOf(company.getAreaId()));
				}
                company.setLocation(area);
            }
            results.setCount(companies.getTotalElements());
            results.setData(companies.getContent());
        }

        return results;
    }

    @ApiOperation(value = "后台单位学校删除")
    @DeleteMapping(value = "/")
    public ResultDto delete(@RequestBody CommonRequestDto requestDto){
        if(requestDto == null || requestDto.getId() == null){
            throw new IllegalArgumentException("删除单位ID必须");
        }
        companyRepository.deleteById(requestDto.getId());
        return ResultDto.builder().data(null).build();

    }

    @ApiOperation(value = "后台单位新增")
    @PostMapping("/")
    public ResultDto add(@RequestBody  CompanyRequestDto requestDto){
        if(requestDto == null || requestDto.getId() != null){
            throw new IllegalArgumentException("单位新增无需填写ID");
        }

        Company company = new Company();
        company.setCreateTime(new Date());
        company.setUpdateTime(new Date());
        BeanUtils.copyProperties(requestDto , company);
        companyRepository.save(company);
        return ResultDto.builder().data(null).build();

    }

    @ApiOperation(value = "单位修改")
    @PutMapping("/")
    public ResultDto update(@RequestBody  CompanyRequestDto requestDto){
        validateRequestParam(requestDto);

        Company oldCompany = companyRepository.findById(requestDto.getId()).get();
        Company company = new Company();
        company.setUpdateTime(new Date());
        //保留上一次的创建时间
        company.setCreateTime(oldCompany.getCreateTime());
        BeanUtils.copyProperties(requestDto , company);

        //后台
        if(requestDto.getRequestSource() == 1){
            companyRepository.save(company);
        }else if(requestDto.getRequestSource() == 2){
            //前台请求　更改发票税号　发票抬头
            oldCompany.setInvoiceHeader(requestDto.getInvoiceHeader());
            oldCompany.setInvoiceTaxNo(requestDto.getInvoiceTaxNo());
            companyRepository.save(oldCompany);
        }

        return ResultDto.builder().build();
    }

    @ApiOperation(value = "单位修改")
    @PostMapping("/modC")
    public ResultDto modC(@RequestBody  CompanyRequestDto requestDto){

        System.out.println(requestDto.getId()+" -==================================================");
        Company oldCompany = companyRepository.findById(requestDto.getId()).get();

        Company company = new Company();
        company.setUpdateTime(new Date());
        //保留上一次的创建时间
        company.setCreateTime(oldCompany.getCreateTime());
        BeanUtils.copyProperties(requestDto , company);


        //前台请求　更改发票税号　发票抬头
        company.setInvoiceHeader(requestDto.getInvoiceHeader());
        company.setInvoiceTaxNo(requestDto.getInvoiceTaxNo());
        companyRepository.save(company);

        return ResultDto.builder().success(true).message("修改成功").build();
    }


    @Autowired
    private UserService userService;

    @Autowired
    private UserRepositoty userRepositoty;

    /**
     * 前台单位修改页面进入读取数据用
     * @param request
     * @return
     */
    @ApiOperation(value = "单位修改")
//    @PutMapping("/front")
    @PostMapping("/front")
    public Company front(HttpServletRequest request){
        String phone = userService.getCurrentUsername(request);
        Long l= userRepositoty.findByPhone(phone).getCompany().getId();


        Long id = companyRepository.findById(l).get().getId();
        String name = companyRepository.findById(l).get().getName();
        String zhizhao = companyRepository.findById(l).get().getZhiZhao();
        String person = companyRepository.findById(l).get().getContactPerson();
        String tel = companyRepository.findById(l).get().getContactTel();

        CompanyTypeEnum danwei = companyRepository.findById(l).get().getCompanyType();

        String taitou = companyRepository.findById(l).get().getInvoiceHeader();
        String fapiao = companyRepository.findById(l).get().getInvoiceTaxNo();

        Company company = new Company();
        company.setId(id);
        company.setName(name);
        company.setZhiZhao(zhizhao);
        company.setContactPerson(person);
        company.setContactTel(tel);

        company.setCompanyType(danwei);
        company.setInvoiceHeader(taitou);
        company.setInvoiceTaxNo(fapiao);

        ResultDto resultDto = new ResultDto();
        resultDto.setData(company);
        return company;

//        return ResultDto.builder().success(true).build();
    }

    /**
     * 前台单位修改页面提交数据
     * @param request
     * @param company
     * @return
     */
    @ApiOperation(value = "单位修改")
    @PostMapping("/frontDo")
    public ResultDto front(HttpServletRequest request,Company company){
        String phone = userService.getCurrentUsername(request);
        Long companyid = userRepositoty.findByPhone(phone).getCompany().getId();
        Long id = companyRepository.findById(companyid).get().getId();

        Company oldCompany = companyRepository.findById(id).get();
        BeanUtils.copyProperties(company, oldCompany);
        companyRepository.save(oldCompany);

        return ResultDto.builder().success(true).build();
    }


    private void validateRequestParam(CompanyRequestDto requestDto) {

        if(requestDto.getRequestSource() == null){
            throw new IllegalArgumentException("单位修改请求来源必填,1 后台, 2 前台");
        }

        if(requestDto.getId() == null){
            throw new IllegalArgumentException("单位修改ID必填");
        }

        if(requestDto.getRequestSource() == 1){

        }else if(requestDto.getRequestSource() == 2){
            if(StringUtils.isEmpty(requestDto.getInvoiceHeader())  && StringUtils.isEmpty(requestDto.getInvoiceTaxNo())){
                throw new IllegalArgumentException("发票抬头,发票税号必填其一");
            }
        }else{
            throw new IllegalArgumentException("单位修改请求来源非法");
        }

        //是否存在
        Company oldCompany = companyRepository.findById(requestDto.getId()).get();

        if(oldCompany == null){
            throw new IllegalArgumentException("单位更新失败,给定ID:"+requestDto.getId()+"记录不存在");
        }
    }

}
